<template>
  <el-dialog :title="title" :visible.sync="centerDialogVisible" width="30%" center @close="close">
    <div class="qrcodeBox">
      <canvas id="qrcode" ref="qrcode" v-if="centerDialogVisible"></canvas>
      <!-- <div id="qrcode" ref="qrcode" v-if="centerDialogVisible"></div> -->
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="centerDialogVisible = false">关 闭</el-button>
      <el-button type="primary" @click="downloadQRcode">下 载</el-button>
    </span>
  </el-dialog>
</template>

<script>
import QRCode from 'qrcodejs2'
export default {
  props: {
    title: { type: String, default: '二维码' }
  },
  data() {
    return {
      logoUrl: '../../assets/logo/logo.jpg',
      url: '',
      centerDialogVisible: false
    }
  },
  methods: {
    downloadQRcode() {
      var oQrcode = document.querySelector('#qrcode img')
      var url = oQrcode.src
      var a = document.createElement('a')
      var event = new MouseEvent('click')
      // 下载图名字
      a.download = '张三的二维码'
      //url
      a.href = url
      //合成函数，执行下载
      a.dispatchEvent(event)
    },
    qrcode(url) {
      let qrcode = new QRCode('qrcode', {
        width: 200, // 设置宽度，单位像素
        height: 200, // 设置高度，单位像素
        text: url, // 设置二维码内容或跳转地址
        logo: this.logoUrl
      })
    },
    open(url) {
      this.centerDialogVisible = true
      this.url = url
      if (url) {
        this.$nextTick(() => {
          this.qrcode(url)
        })
      }
    },
    close() {
      this.centerDialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.qrcodeBox {
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  #qrcode {
    display: inline-block;
  }
}
</style>
